package aiyh.utils.recordset;

import aiyh.utils.annotation.DateFormatAn;
import aiyh.utils.excention.TypeNonsupportException;
import com.ibm.icu.text.SimpleDateFormat;
import weaver.conn.RecordSet;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.util.Date;

/**
 * @author EBU7-dev1-ayh
 * create 2021/12/21 0021 13:35
 */


public class DataTypeHandler implements TypeHandler {
    @Override
    public Object getValue(RecordSet rs, String fieldName, Field declaredField) {
        if (declaredField == null) {
            throw new TypeNonsupportException("An error occurred while trying to convert the query result field to type Date!");
        }
        DateFormatAn annotation = declaredField.getAnnotation(DateFormatAn.class);
        Date date = null;
        if (annotation != null) {
            String value = annotation.value();
            try {
                date = new SimpleDateFormat(value).parse(rs.getString(fieldName));
            } catch (ParseException e) {
                e.printStackTrace();
                throw new TypeNonsupportException("Failed to convert [" + rs.getString(fieldName) + "] to a Date object as [" + value + "]!!");
            }
        }
        return date;
    }

    @Override
    public Object getValue(RecordSet rs, int index, Field declaredField) {
        if (declaredField == null) {
            throw new TypeNonsupportException("An error occurred while trying to convert the query result field to type Date!");
        }
        DateFormatAn annotation = declaredField.getAnnotation(DateFormatAn.class);
        Date date = null;
        if (annotation != null) {
            String value = annotation.value();
            try {
                date = new SimpleDateFormat(value).parse(rs.getString(index));
            } catch (ParseException e) {
                e.printStackTrace();
                throw new TypeNonsupportException("Failed to convert [" + rs.getString(index) + "] to a Date object as [" + value + "]!!");
            }
        }
        return date;
    }
}
